package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    // 创建一个DatagramSocket 对象 ,后续操作网卡的基础
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        // 这么写是手动指定端口
        socket = new DatagramSocket(port);
        //这么写是让系统自动分配端口
        //socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {
            //1.读取数据并分析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //当完成receive后,数据就以二进制的形式存储到DatagramPacket中了
            //要想把这些数据显示出来, 还需要把二进制转换成字符串
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //2.根据请求计算响应
            String response = process(request);
            //3.把响应写回到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //4.打印日志
            System.out.printf("[%s:%d] req = %s, resp = %s \n", responsePacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
